#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import nmap

scan_row=[]
input_data = raw_input('Please input hosts and port: ')
scan_row = input_data.split(" ")
if len(scan_row) != 2:
    print "Input errors, example '192.168.1.0/24 80,443,22'"
    sys.exit(0)

hosts = scan_row[0]
port = scan_row[1]

# 创建端口扫描对象
try:
    nm = nmap.PortScanner()
except nmap.PortScannerError:
    print("Nmap not found", sys.exc_info()[0])
    sys.exit(0)
except:
    print("Unexpected error: ", sys.exc_info()[0])
    sys.exit(0)

# 调用扫描方法，参数指定扫描主机hosts， nmap扫描命令行参数arguments
try:
    nm.scan(hosts=hosts, arguments=' -v -sS -p '+port)
except Exception, e:
    print "Scan error: " + str(e)

# 遍历扫描主机
for host in nm.all_hosts():
    print('-----------------------------------')
    print('Host : %s (%s)' % (host, nm[host].hostname()))
    print('Stat : %s' % nm[host].state())
    # 遍历扫描协议
    for proto in nm[host].all_protocols():
        print('-----------')
        print('Protocol : %s' % proto)
        lport = nm[host][proto].keys()
        print('Proto : %s' % lport)
        lport.sort()
        for port in lport:
            print("%s" % nm[host])
            #print("port : %s\tstat : %s" % (port, nm[host][proto][port]['state']))